package com.example.asa;

import com.example.asa.Disaster;
import com.example.asa.DatabaseUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ViewReportsServlet")
public class ViewReportsServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String role = (String) session.getAttribute("role");

        // 权限检查：仅允许应急人员访问
        if (role == null || !"emergency".equals(role)) {
            request.setAttribute("error", "您没有权限访问此页面");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        List<Disaster> disasterList = new ArrayList<>();

        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM disasters ORDER BY timestamp DESC")) {

            while (rs.next()) {
                Disaster disaster = new Disaster();
                disaster.setId(rs.getInt("id"));
                disaster.setName(rs.getString("name"));
                disaster.setDescription(rs.getString("description"));
                disaster.setLocation(rs.getString("location"));
                disaster.setSeverity(rs.getString("severity"));
                disaster.setTimestamp(rs.getTimestamp("timestamp"));
                disaster.setStatus(rs.getString("status"));
                disaster.setContact(rs.getString("contact"));
                disaster.setReportUser(rs.getString("report_user"));

                disasterList.add(disaster);
            }

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "加载灾情信息失败：" + e.getMessage());
            request.getRequestDispatcher("error.jsp").forward(request, response);
            return;
        }

        request.setAttribute("disasterList", disasterList);
        request.getRequestDispatcher("viewReports.jsp").forward(request, response);
    }
}
